package com.inepex.inechart.client.linechart;

import java.util.ArrayList;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.inepex.inechart.client.displayengine.CartesianRectangleTile;
import com.inepex.inechart.client.linechart.LineChartToGoGWT.LineChartGOCreationType;
import com.inepex.inechart.shared.linechart.Curve;
import com.inepex.inegraphics.impl.client.IncrementalProgress.IncrementalProgressCaller;

public abstract class IncrementalLineChartGOCreator implements IncrementalProgressCaller{

	protected int partTreshold;
	protected int finishedCurveIndex;
	protected ArrayList<Curve> curves;
	protected LineChartToGoGWT target;
	protected LineChartGwt lineChartGwt;
	protected LineChartGOCreationType goCreatePhase;
	protected CartesianRectangleTile jobTile;

	public IncrementalLineChartGOCreator(int partTreshold, LineChartGwt lineChartGwt,
			ArrayList<Curve> curves, CartesianRectangleTile jobTile) {
		super();
		this.lineChartGwt = lineChartGwt;
		this.partTreshold = partTreshold;
		this.curves = curves;
		this.jobTile = jobTile;
		goCreatePhase = LineChartGOCreationType.strokePathCalc;
		finishedCurveIndex = 0;
		startCalculating();
	}

	protected void startCalculating(){
		if(next()){
			Scheduler.get().scheduleIncremental(new RepeatingCommand() {
				@Override
				public boolean execute() {
					boolean inProgress = IncrementalLineChartGOCreator.this.target.nextProgressPart();
					if(!inProgress){
						inProgress = next();
						if(!inProgress){
							onFinished();					
						}
					}
					return inProgress;				
				}
			});
		}
	}

	protected boolean next(){
		if(finishedCurveIndex >= curves.size()){
			if(goCreatePhase == LineChartGOCreationType.strokePathCalc){
				goCreatePhase = LineChartGOCreationType.fillPathCalc;
				finishedCurveIndex = 0;
			}
			else if(goCreatePhase == LineChartGOCreationType.fillPathCalc){
				goCreatePhase = LineChartGOCreationType.curveToGO;
				finishedCurveIndex = 0;
			}
			else{
				return false;
			}
		}
		Curve act = curves.get(finishedCurveIndex);
		CurvePart curvePart = lineChartGwt.curveModelMap.get(act).getCurvePart(jobTile.getxFrom());
		target = lineChartGwt.curveToGOMap.get(act);
		target.initJob(
				goCreatePhase, curvePart,
				jobTile.getLeft(), 
				jobTile.getRight(),
				jobTile.getTop(),
				jobTile.getBottom());
		target.initProgress(this);
		finishedCurveIndex++;
		return true;
	}

	@Override
	public int getProgressPartTresholdMS() {
		return partTreshold;
	}

	public abstract void onFinished();



}
